var map = new AMap.Map("container", {
	//resizeEnable : true,
    zoom: 4
});


//根据城市名称查询
var MSearch;
var key_1;
function placeSearch() {  //POI搜索，关键字查询
    key_1 = document.getElementById("citycode").value;
    key_1 = key_1.substring(0,key_1.indexOf("-"));
    map.plugin(["AMap.PlaceSearch"], function() {    //构造地点查询类  
        MSearch = new AMap.PlaceSearch({ 
        });
        AMap.event.addListener(MSearch, "complete", function(data){
            var poiArr = data.poiList.pois;
            var lngX = poiArr[0].location.getLng();
            var latY = poiArr[0].location.getLat();
            map.setCenter(new AMap.LngLat(lngX, latY));
            map.setZoom(9)
        });//返回地点查询结果        
        MSearch.search(key_1); //关键字查询
    });
}

var pointList = [];
var fenceModel = [];//坐标
var markers = [];
var coordinate = [];
var positionPoint;
var count = 1;
var isDup = false;
polygon = new AMap.Polygon({
	cursor : 'move',
	strokeColor : "#35fffd", // 线颜色
	strokeOpacity : 0.8, // 线透明度
	strokeWeight : 2, // 线宽
	fillColor : "#35fffd", // 填充色
	fillOpacity : 0.5
// 填充透明度
});
polygon.setMap(map);

var polyEditor = new AMap.PolyEditor(map, polygon)//编辑插件
// 缩放地图到合适的视野级别
map.setFitView([polygon]);

$("#update_btn").on('click',function(){
	var cityname = $("#citycode").val();
	if(cityname == null || cityname == ""){
		layer.msg("请选择城市！");
		return false;
	}
	polyEditor.open();
	map.remove(markers);// 清除点标记 显示编辑点标记
})
$("#update_end").on('click',function(){
	var cityname = $("#citycode").val();
	if(cityname == null || cityname == ""){
		layer.msg("请选择城市！");
		return false;
	}
	polyEditor.close();
	fenceModel = [];		
	var Path =  polygon.getPath();//获取当前所有坐标
	var latitude = null; var longitude = null;
	for(var i = 0 ;i < Path.length ; i++ ){
		if(typeof Path[i].lng == "undefined"){				//数组
			latitude = Path[i][1];
			longitude = Path[i][0];
		}else{
			latitude = Path[i].lat;
			longitude = Path[i].lng;
		}
		var point = {
				"no" : i,
				"latitude" :  latitude,
				"longitude" : longitude
			};
		fenceModel.push(point);
	}
	addMap(fenceModel,cityname);
})


//添加地图
$("#query_btn").on('click',function(){
	var cityname = $("#citycode").val();
	if(cityname == null || cityname == ""){
		layer.msg("请选择城市！");
		return false;
	}
	addMap(fenceModel,cityname);
	 
})

//开始绘制
$("#begin_btn").on('click',function(){
	var cityname = $("#citycode").val();
	if(cityname == null || cityname == ""){
		layer.msg("请选择城市！");
		return false;
	}
	$("#update_btn").hide()
	$("#update_end").hide()
	$("#Carsreset").show();
	$("#cancelPoint").show();
	$("#query_btn").show();
	$("#cancel_btn").show();
	$("#begin_btn").hide();
	// 注册click事件
	map.on('click', mapClick);
})

//取消绘制
$("#cancel_btn").on('click',function(){
	window.location.reload();
})

// 请求地址
$("#searchcity").on('click',function(){
	selectCity();
})


function selectCity(){
	reset();
	var cityname = $("#citycode").val();
	if(cityname == null || cityname == ""){
		layer.msg("请选择城市！");
		return false;
	}
	placeSearch();//根据城市名称查询
	$.ajax({
		type : "post",
		url : "getChangchunPosition",
		data : {"cityname" : cityname},
		dataType : "json",
		success : function(data) {
			$.each(data, function(index, item) {
				AMapUI.loadUI([ 'overlay/SimpleMarker' ],
						function(SimpleMarker) {
							var marker = new SimpleMarker({
								// 图标主题
								iconTheme : 'numv1',
								// 背景图标样式
								iconStyle : 'blue',
								position : [ item.longitude, item.latitude ],// marker所在的位置
							});
							marker.setMap(map);
							markers.push(marker);
							// 绘制多边形
							pointList.push([item.longitude, item.latitude ]);
							polygon.setPath(pointList);
						});
				var point = {
					"no" : index,
					"latitude" :  item.latitude,
					"longitude" : item.longitude
				};
				fenceModel.push(point);
				count = index;
			})

		}
	});
}


// 绘制地图
var mapClick = function(e) {
	for (var i = 0; i < fenceModel.length; i++) {// 判断是不是同一个点
		if (fenceModel[i].latitude === e.lnglat.lat
				&& fenceModel[i].longitude === e.lnglat.lng) {
			isDup = true;
		}
	}
	if (!isDup || fenceModel.length === 0) {
		AMapUI.loadUI([ 'overlay/SimpleMarker' ], function(SimpleMarker) {
			var marker = new SimpleMarker({
				// 图标主题
				iconTheme : 'numv1',
				// 背景图标样式
				iconStyle : 'blue',
				position : [ e.lnglat.lng, e.lnglat.lat ],// marker所在的位置
			});
			marker.setMap(map);
			markers.push(marker);
			// 绘制多边形
			pointList.push([ e.lnglat.lng, e.lnglat.lat ]);
			polygon.setPath(pointList);
		});

		// 保存点数据
		var point = {
			"no" : count,
			"latitude" : e.lnglat.lat,
			"longitude" : e.lnglat.lng
		};
		fenceModel.push(point);
		count++;
	}
};

// 注册click事件
map.on('click', null);

// 重置
$("#Carsreset").on('click', function() {
	reset()
})

//重置
function  reset(){
	count = 1;
	fenceModel = [];
	pointList = [];
	map.remove(markers);
	map.setCenter(positionPoint);
	polygon.setPath([]);
}
// 回退
$("#cancelPoint").on('click', function() {
	if (fenceModel.length) {
		var removePoint = fenceModel.pop();
		var removeMarker = markers.pop();
		map.remove(removeMarker);
		pointList.pop();
		polygon.setPath(pointList);
		count--;
	}
})

function addMap(fenceModel,cityname){
	if(fenceModel.length < 4){
		alert("坐标点不能少于四个",{time: 1500});
		return falsel;
	}
	$.ajax({
    	type : "post",
    	url : "createMapMonitor",
    	traditional: true,
    	data : {"coordinate": JSON.stringify(fenceModel),"cityname" : cityname},
    	dataType : "json",
    	success : function (data){
    		alert(data.msg);
    		if(data.status == "SUCCESS"){
    			window.location.reload();
    		}
    		if(data.status == "error"){
    			window.location.reload();
    		}
    	}
    })
}
